package net.sureon.web.admin;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sureon.app.AppContext;
import net.sureon.biz.CompanyConfigBO;
import net.sureon.biz.CompanyMgr;
import net.sureon.common.config.SureonConfig;
import net.sureon.common.exception.SureonException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

public class FileUploadController extends SimpleFormController {
	private static Log log = LogFactory.getLog(FileUploadController.class);
	private CompanyMgr companyMgr;
	private String allowFileFormat;

	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object cmd, BindException errors)
			throws Exception {

		long companyID = AppContext.getCompanyID();

		String siteURL = companyMgr.getCompany(companyID).getCompanyVO()
				.getSiteURL();

		String uploadDir = SureonConfig.getInstance().getProperty(
				SureonConfig.CONF_NAME_BASE_BRAND_DIR)
				+ "/" + siteURL + "/";

		String key = null;
		String value = null;

		// cast to multipart file so we can get additional information
		// 网页左上角图标
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		CommonsMultipartFile logoForLeftUp = (CommonsMultipartFile) multipartRequest
				.getFile("logoForLeftUp");
		// 网页右上角横幅图
		CommonsMultipartFile advertisingForRightUp = (CommonsMultipartFile) multipartRequest
				.getFile("advertisingForRightUp");
		CommonsMultipartFile indexLogo = (CommonsMultipartFile)multipartRequest.getFile(CompanyConfigBO.INDEX_LOGO);
		if (logoForLeftUp != null) {
			int i = checkLimit(request, allowFileFormat, logoForLeftUp
					.getOriginalFilename());

			if (i == -1) {
				log.error("不支持上传的文件格式");
				throw new SureonException("upload_file_type_not_supported");
			}

			File dirPath = new File(uploadDir);
			if (!dirPath.exists()) {
				dirPath.mkdirs();
			}
			if (log.isDebugEnabled()) {
				log.debug("uploading to: " + uploadDir + "logo" + "."
						+ getSuffix(logoForLeftUp.getOriginalFilename()));
			}
			
			String systemTime = System.currentTimeMillis() + "";
			
			File uploadedFile = new File(uploadDir + "logo_" + systemTime + "."
					+ getSuffix(logoForLeftUp.getOriginalFilename()));

			DataOutputStream out = null;
			InputStream is = null;
			try {
				out = new DataOutputStream(new FileOutputStream(uploadedFile));
				is = logoForLeftUp.getInputStream();
				byte[] buffer = new byte[1024];
				while (is.read(buffer) > 0) {
					out.write(buffer);
				}
				is.close();
				out.close();
			} catch (Exception e) {
				log.error(e);
				throw new SureonException("文件上传失败！请重新上传");
			}
			// 将信息保存进入数据库
			key = "logoForLeftUp";
			value = "/" + siteURL + "/logo_" + systemTime +  "." + getSuffix(logoForLeftUp.getOriginalFilename());
//			value = uploadDir + "logo" + "."
//			+ getSuffix(logoForLeftUp.getOriginalFilename());
		} else if(advertisingForRightUp != null){
			// 上传网页右上角横幅图
			int i = checkLimit(request, allowFileFormat, advertisingForRightUp
					.getOriginalFilename());

			if (i == -1) {
				log.error("不支持上传的文件格式");
				throw new SureonException("目前尚不支持该文件格式的文件上传");
			}

			File dirPath = new File(uploadDir);
			if (!dirPath.exists()) {
				dirPath.mkdirs();
			}
//			String sep = System.getProperty("file.separator");
			if (log.isDebugEnabled()) {
				log.debug("uploading to: " + uploadDir + "advertising"
						+ getSuffix(advertisingForRightUp.getOriginalFilename()));
			}
			
			String systemTime = System.currentTimeMillis() + "";
			
			File uploadedFile = new File(uploadDir + "advertising_" + systemTime
					+ "." +  getSuffix(advertisingForRightUp.getOriginalFilename()));
			// FileCopyUtils.copy(bytes, uploadedFile);

			DataOutputStream out = null;
			InputStream is = null;
			try {
				out = new DataOutputStream(new FileOutputStream(uploadedFile));
				is = advertisingForRightUp.getInputStream();
				byte[] buffer = new byte[1024];
				while (is.read(buffer) > 0) {
					out.write(buffer);
				}
				is.close();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			// 将信息保存进入数据库
			key = "advertisingForRightUp";
			value = "/" + siteURL + "/advertising_" + systemTime + "." + getSuffix(logoForLeftUp.getOriginalFilename());
//			value = uploadDir + "advertising"
//			+ "." +  getSuffix(advertisingForRightUp.getOriginalFilename());
		} else {
			int i = checkLimit(request, allowFileFormat, indexLogo
					.getOriginalFilename());

			if (i == -1) {
				log.error("不支持上传的文件格式");
				throw new SureonException("目前尚不支持该文件格式的文件上传");
			}

			File dirPath = new File(uploadDir);
			if (!dirPath.exists()) {
				dirPath.mkdirs();
			}
			if (log.isDebugEnabled()) {
				log.debug("uploading to: " + uploadDir + "indexLogo"
						+ getSuffix(indexLogo.getOriginalFilename()));
			}
			
			String systemTime = System.currentTimeMillis() + "";
			File uploadedFile = new File(uploadDir + "indexLogo_" + systemTime
					+ "." +  getSuffix(indexLogo.getOriginalFilename()));
			// FileCopyUtils.copy(bytes, uploadedFile);

			DataOutputStream out = null;
			InputStream is = null;
			try {
				out = new DataOutputStream(new FileOutputStream(uploadedFile));
				is = indexLogo.getInputStream();
				byte[] buffer = new byte[1024];
				while (is.read(buffer) > 0) {
					out.write(buffer);
				}
				is.close();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			key = "indexLogo";
			value = "/" + siteURL + "/indexLogo_" + systemTime + "." + getSuffix(indexLogo.getOriginalFilename());
//			value = uploadDir + "indexLogo"
//			+ "." +  getSuffix(indexLogo.getOriginalFilename());

		}

		companyMgr.mergeCompanyConfig(companyID, key, value);

		response.sendRedirect(request.getContextPath() + "/admin/systemSet.do");
		return null;
	}

	private int checkLimit(HttpServletRequest request, String limit,
			String fileName) {
		String[] ls = limit.split(";");
		String fileMode = getSuffix(fileName);

		boolean iden = false;
		for (int i = 0; i < ls.length; i++) {
			if (fileMode.equalsIgnoreCase(ls[i])) {
				iden = true;
				break;
			}
		}
		if (!iden) { // 不符合
			return -1;
		}
		return 0;
	}

	/**
	 * 截取上傳文件名后綴
	 */
	private String getSuffix(String fileName) {
		return fileName.substring(fileName.lastIndexOf(".") + 1);
	}

	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws ServletException {
		binder.registerCustomEditor(byte[].class,
				new ByteArrayMultipartFileEditor());
	}

	public CompanyMgr getCompanyMgr() {
		return companyMgr;
	}

	public void setCompanyMgr(CompanyMgr companyMgr) {
		this.companyMgr = companyMgr;
	}

	public String getAllowFileFormat() {
		return allowFileFormat;
	}

	public void setAllowFileFormat(String allowFileFormat) {
		this.allowFileFormat = allowFileFormat;
	}
}
